package com.kkwrite.regimen.common.util;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by lisha on 2018/7/11 15:57.
 *
 * @author lisha
 */
public class MD5Util {
    private MD5Util() {}

    /**
     * 计算字符串的MD5值
     * @param source 源字符串
     * @return 32位的十六进制字符串MD5
     * @throws NoSuchAlgorithmException 获取MD5 MessageDigest时可能抛出该异常
     * @throws UnsupportedEncodingException 将source以utf-8编码转为byte数组时可能抛出该异常
     */
    public static String digest(String source) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(source.getBytes("UTF-8"));
        byte[] resultByte = md5.digest();
        BigInteger bigInteger = new BigInteger(1, resultByte);
        return bigInteger.toString(16);
    }

}
